package com.zxbit.flash.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.WindowManager;

import com.zxbit.flash.R;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.network.ParamsFactory;
import com.zxbit.flash.network.RetrofitHelper;
import com.zxbit.flash.response.AuthResponse;

import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SplashActivity extends BaseTitleActivity {

    @Override
    protected void initViews() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏显示
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    @Override
    protected void onUIReady() {
        getVerifyData();
    }

    @SuppressLint("CheckResult")
    public void getVerifyData() {
        getVerifyOb().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<AuthResponse>() {
                    @Override
                    public void accept(AuthResponse verifyDataResponse) throws Exception {
                        if (verifyDataResponse.getStatus() == Constant.LOGIN_TIMEOUT) { //token 会过期
                            UserInfo.logout();
                        }
                        jumpToMain();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        // 异常操作
                        jumpToMain();
                    }
                });
    }

    private void jumpToMain() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);

                SplashActivity.this.startActivity(mainIntent);
                overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
                finish();
            }
        };

        timer.schedule(timerTask, 1000);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_splash;
    }

    private Observable<AuthResponse> getVerifyOb() {
        return RetrofitHelper.getRetorfitHelper().getApiService()
                .getAuthStatus(UserInfo.getToken(), ParamsFactory.getCommonParams(null));
    }
}
